package com.kancy.publicapi.web.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * TimeoutController
 * </p>
 *
 * @author: kancy
 * @date: 2019/12/5 17:25
 **/
@RestController
public class TimeoutController {

    /**
     * 超时
     * @param millis
     * @return
     */
    @RequestMapping(value = "/timeout/{millis}", method = {RequestMethod.GET, RequestMethod.POST})
    public String sleep(@PathVariable("millis") String millis){

        Duration duration = null;
        try {
            duration = Duration.ofMillis(Long.parseLong(millis));
        }catch (NumberFormatException e) {
            try {
                String value = millis.substring(0, millis.length()-1);
                String scale = millis.substring(millis.length()-1);
                if ("s".equalsIgnoreCase(scale)){
                    duration = Duration.ofSeconds(Long.parseLong(value));
                }
                if ("m".equalsIgnoreCase(scale)){
                    duration = Duration.ofMinutes(Long.parseLong(value));
                }
                if ("h".equalsIgnoreCase(scale)){
                    duration = Duration.ofHours(Long.parseLong(value));
                }
                if ("d".equalsIgnoreCase(scale)){
                    duration = Duration.ofDays(Long.parseLong(value));
                }
            } catch (NumberFormatException n) {
                n.printStackTrace();
            }
        }
        if (!Objects.isNull(duration)){
            try {
                TimeUnit.MILLISECONDS.sleep(duration.toMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return "ok";
    }
}
